package com.erf.handler.server;

import com.erf.message.*;
import com.erf.tools.SpringContextHelper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class BusinessHandler extends AbstractBusinessHandler {

    public static SpringContextHelper springContextHelperStatic;
    @Autowired
    SpringContextHelper springContextHelper;

    /**
     * 简写方式只是用于注入springContextHelper
     * 再用springContextHelper获取其他springBean
     */
    @PostConstruct
    public void init() {
        springContextHelperStatic = this.springContextHelper;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, BaseMessage msg) {
        log.info("[server_receive]" + msg);
        if (msg instanceof SubmitRequest) {
            SubmitRequest submitRequest = (SubmitRequest) msg;

            SubmitRequestResponse submitRequestResponse = new SubmitRequestResponse();
            submitRequestResponse.setSequence(msg.getSequence());
            try {
                Class<?> aClass = Class.forName(submitRequest.getClassName());
                Method call = aClass.getMethod(submitRequest.getMethodName(), submitRequest.getParamsTypes());
                Object result;
                String invokeName = submitRequest.getSpringInvokeName();
                if (invokeName != null && invokeName.trim().length() != 0) {
                    Object bean = springContextHelperStatic.getBean(invokeName);
                    result = call.invoke(bean, submitRequest.getParamsValues());
                } else {
                    result = call.invoke(aClass.newInstance(), submitRequest.getParamsValues());
                }
                submitRequestResponse.setCode(0);
                submitRequestResponse.setResult(result);
            } catch (Exception e) {
                e.printStackTrace();
                submitRequestResponse.setCode(-1);
                submitRequestResponse.setResult(e);
            }
            ctx.writeAndFlush(submitRequestResponse);

        } else if (msg instanceof ActiveTest) {
            ActiveTestResponse activeTestResponse = new ActiveTestResponse();
            activeTestResponse.setSequence(msg.getSequence());
            ctx.writeAndFlush(activeTestResponse);
        }
    }
}
